import { Switch,Route,Redirect,withRouter } from "react-router-dom";
import {userinfo} from "../utils/getUserInfo"

function RouterView(props){
    const {routes} = props
    return <Switch>
        {
            routes.map((item,index)=>{
                //循环路由：Route除了定义组件之外，还起到占位作用
                if(item.component){
                    return <Route key={index} exact={item.exact} path={item.path} render={()=>{
                        if(item.meta.mustLogin){
                            //是否登录
                            if(!userinfo().token){
                                return <Route key={index} exact={item.exact} path={item.path}>
                                        <Redirect to='/login'/>       
                                    </Route>
                            }//没有登录
                        }

                        item.meta.title && (document.title = item.meta.title) //设置title
                        const Component = withRouter(item.component)  
                        return <Component {...props} />
                    }}/>
                }else{
                    return <Route key={index} exact={item.exact} path={item.path}>
                         <Redirect to={item.redirect}/>       
                    </Route>
                }
            
            })
        }
    </Switch>
}

export default RouterView